package com.h3c.ptability.task;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.h3c.ptability.entity.PtEsignRecord;
import com.h3c.ptability.entity.PtWaitSignInfo;
import com.h3c.ptability.enums.ElectronicSignRecordStatus;
import com.h3c.ptability.mapper.PtWaitSignInfoMapper;
import com.h3c.ptability.service.IElectronicSignService;
import com.h3c.ptability.service.IPtEsignRecordService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * 找到场景下已经逾期的发起但未签署电子签并作废
 */
@JobHandler(value="syncCancelSignStatus")
@Component
@Slf4j
public class SyncCancelSignStatus extends IJobHandler {

    @Resource
    IElectronicSignService electronicSignService;
    @Resource
    private PtWaitSignInfoMapper signInfoMapper;
    @Resource
    private IPtEsignRecordService signRecordService;

    @Override
    public ReturnT<String> execute(String s) throws Exception{
        Date now = new Date();
        LambdaQueryWrapper<PtWaitSignInfo> infoQuery = new QueryWrapper<PtWaitSignInfo>().lambda();
        infoQuery.isNotNull(PtWaitSignInfo::getPlanEndTime)
                .lt(PtWaitSignInfo::getPlanEndTime, now)
                .isNotNull(PtWaitSignInfo::getRecordId);
        List<PtWaitSignInfo> timeOutSignInfo = signInfoMapper.selectList(infoQuery);

        timeOutSignInfo.forEach(signInfo -> {
            String recordId = signInfo.getRecordId();
            PtEsignRecord record = signRecordService.getById(recordId);
            if (record.getSignStatus() != null && record.getSignStatus().equals(ElectronicSignRecordStatus.SIGNING)){
                try {
                    String cancelResult = electronicSignService.cancelESign(Long.parseLong(record.getSignFlowId()), "签署超时");
                    if (!JSONUtil.parseObj(cancelResult).getJSONObject("data").getBool("success")) {
                        log.error("取消e签宝签署流程失败, 失败原信息为{}", cancelResult);
                    }
                    log.info("工位为{}员工电子签进行作废，结果为{}", signInfo.getWorkerId(), cancelResult);
                } catch (Exception e) {
                    log.error("取消e签宝签署流程出现异常,异常原信息为{}", JSONObject.toJSONString(e));
                }
            }
        });
        return null;
    }
}
